package com.zz.hhbl.utils

import android.content.Context
import com.danikula.videocache.HttpProxyCacheServer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/3/3 15:07.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
object VideoCacheManager {
    private var proxy: HttpProxyCacheServer? = null
    fun getProxy(context: Context): HttpProxyCacheServer {
        return proxy ?: synchronized(this) {
            proxy ?: HttpProxyCacheServer.Builder(context)
                .maxCacheSize(1024 * 1024 * 1024) // 设置最大缓存 1GB
                .build().also { proxy = it }
        }
    }

    /**
     * 检查视频是否已缓存
     */
    fun isVideoCached(context: Context, url: String): Boolean {
        return VideoCacheManager.getProxy(context).isCached(url)
    }

    /**
     * 清理所有缓存
     */
    fun clearCache(context: Context) {
        GlobalScope.launch(Dispatchers.IO) {
            getProxy(context).shutdown() // 关闭缓存服务
            context.cacheDir.deleteRecursively() // 删除缓存文件
        }
    }
}